package neu.soft.service.impl;

import neu.soft.entity.DistributionTaskOrder;
import neu.soft.entity.NormalOrder;
import neu.soft.mapper.DistributionTaskOrderMapper;
import neu.soft.mapper.StateUpdateMapper;
import neu.soft.message.OutputSource;
import neu.soft.service.DistributionTaskOrderService;
import neu.soft.vo.MsgBean;
import neu.soft.vo.ResultBean;
import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class DistributionTaskOrderServiceImpl implements DistributionTaskOrderService {
    @Autowired
    DistributionTaskOrderMapper distributionTaskOrderMapper;
    @Autowired
    StateUpdateMapper stateUpdateMapper;
    @Autowired
    private OutputSource source;

    private String ord;

    public <T> boolean sendObject(T msg, Integer delay) throws Exception {
        Message<T> message = MessageBuilder.withPayload(msg)
                .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, delay)
                .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
                .build();

        return source.sendDistribution().send(message);
    }


    @Override
    public ResultBean autoCreateDistributionTaskOrder(NormalOrder normalOrder) throws Exception {
        ResultBean re = new ResultBean();
        List<DistributionTaskOrder> dis = distributionTaskOrderMapper.findDistributionOrder(normalOrder);
        List<DistributionTaskOrder> distributionTaskOrders = new ArrayList<DistributionTaskOrder>();
        for (DistributionTaskOrder d : dis) {
            HashMap<String, Object> map = new HashMap();
            map.put("oid", d.getOrderId());
            int temp = distributionTaskOrderMapper.queryExistDistributionTaskOrder(map);
            System.out.println(temp);
            if (temp != 0) {
                break;
            }
            distributionTaskOrders.add(d);
            distributionTaskOrderMapper.createDistributionTaskOrder(d);
            re = ResultBean.success();
            re.setMsg("创建成功");

        }
        if (re.getCode() == 200) {
            re.setData(distributionTaskOrders);
            this.sendObject(new MsgBean(distributionTaskOrders, "配送任务单创建成功"), 0);
        }
        re = ResultBean.success(distributionTaskOrders);
        return re;
    }
}
